package com.example.fszq.volleydemo1;

import android.content.Intent;
        import android.os.Bundle;
        import android.support.v4.widget.SwipeRefreshLayout;
        import android.support.v7.app.AppCompatActivity;
        import android.support.v7.widget.Toolbar;
        import android.util.Log;
        import android.view.Menu;
        import android.view.MenuItem;
        import android.view.View;
        import android.widget.AdapterView;
        import android.widget.Button;
        import android.widget.ListView;
        import android.widget.Toast;

        import com.android.volley.NetworkResponse;
        import com.android.volley.RequestQueue;
        import com.android.volley.Response;
        import com.android.volley.VolleyError;
        import com.android.volley.toolbox.HttpHeaderParser;
        import com.android.volley.toolbox.StringRequest;
        import com.example.fszq.volleydemo1.adapters.TopicListAdapter;
        import com.example.fszq.volleydemo1.utils.Parsehtml;
        import com.example.fszq.volleydemo1.layout.RefreshLayout;
        import com.example.fszq.volleydemo1.utils.Requesttoserver;
        import com.example.fszq.volleydemo1.utils.TopicList;
        import com.google.gson.Gson;
        import com.google.gson.reflect.TypeToken;

        import org.json.JSONArray;

        import java.io.UnsupportedEncodingException;
        import java.util.ArrayList;
        import java.util.List;


public class MainActivity extends AppCompatActivity {
    public final static String EXTRA_MESSAGE = "com.example.fszq.molleydemo1.MESSAGE";
    private List<TopicList> topicList = new ArrayList<TopicList>();
    private RequestQueue quence ;
    private Requesttoserver Rserver = new Requesttoserver();
    private Parsehtml Parse = new Parsehtml();
    private View footView;
    int page = 1;
    String boradId = "",boradName = "";

    //
    ListView listView;
    Button shotButton;
    TopicListAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_topic_list);

        quence = Rserver.getRequestQueue(getApplicationContext());

        Intent intent = getIntent();
        final String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);
        boradId = message.substring(0,message.indexOf("||"));
        boradName = message.substring(message.indexOf("||")+2,message.length());

        //处理标题栏
        Toolbar toolbar = (Toolbar) findViewById(R.id.header_title);
        toolbar.setTitle(boradName);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setDisplayShowHomeEnabled(true);

        // 获取RefreshLayout实例
        final RefreshLayout myRefreshListView = (RefreshLayout)
                findViewById(R.id.pull_layout);

        //处理listview
        adapter = new TopicListAdapter(MainActivity.this, R.layout.topic_list, topicList);
        listView = (ListView) findViewById(R.id.list_view);

        //增加footview
        footView = getLayoutInflater().inflate(R.layout.refresh_footer, null);
        listView.addFooterView(footView);
        listView.setAdapter(adapter);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                TopicList stopic = topicList.get(position);
                Intent intent = new Intent(MainActivity.this, DisplayMessageActivity.class);
                Log.d("gettopicid", stopic.getTopicid());
                intent.putExtra(EXTRA_MESSAGE, boradId + "#" + stopic.getTopicid());
                startActivity(intent);
            }
        });
        myRefreshListView.setChildView(listView);

        //初始化首页
        getTopicList();


        // 设置下拉刷新监听器
        myRefreshListView.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {

            @Override
            public void onRefresh() {

                //Toast.makeText(MainActivity.this, "refresh", Toast.LENGTH_SHORT).show();

                myRefreshListView.postDelayed(new Runnable() {

                    @Override
                    public void run() {
                        // 更新数据 清空数据
                        page = 1;
                        getTopicList();
                        //datas.add(new Date().toGMTString());
                        adapter.notifyDataSetChanged();
                        // 更新完后调用该方法结束刷新
                        myRefreshListView.setRefreshing(false);
                    }
                }, 1000);
            }
        });

        myRefreshListView.setOnLoadListener(new RefreshLayout.OnLoadListener() {

            @Override
            public void onLoad() {

                Toast.makeText(MainActivity.this, "load", Toast.LENGTH_SHORT).show();

                myRefreshListView.postDelayed(new Runnable() {

                    @Override
                    public void run() {
                        //datas.add(new Date().toGMTString());
                        page++;
                        getTopicList();
                        // 加载完后调用该方法
                        myRefreshListView.setLoading(false);
                    }
                }, 1500);

            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    /** Called when the user clicks the Send button */
    //public void sendMessage(View view) {
    // Do something in response to button
    //Intent intent = new Intent(this, DisplayMessageActivity.class);
    //EditText editText = (EditText) findViewById(R.id.edit_message);
    //String message = editText.getText().toString();
    //intent.putExtra(EXTRA_MESSAGE, message);
    //startActivity(intent);
    //}

    public void getTopicList() {
        String TopicUrl = "http://www.c2000.cn/list.asp?boardid=" + boradId + "&page=" + page  + "&selTimeLimit=&action=&topicmode=0";
        Log.d("sendurl",TopicUrl);

        StringRequest stringRequest = new StringRequest(TopicUrl,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        if(page == 1)
                            topicList.clear();

                        JSONArray returnJsonArray = Parse.getTopicList(response);
                        Gson gson = new Gson();
                        Log.d("return json",returnJsonArray.toString());
                        //List<TopicList>  topic = gson.fromJson(response,new TypeToken<List<TewopicList>>())
                        List<TopicList> topic = gson.fromJson(returnJsonArray.toString(),new TypeToken<List<TopicList>>(){}.getType());
                        for(TopicList t:topic) {
                            topicList.add(t);
                        }

                        adapter.notifyDataSetChanged();


                    }
                }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                Log.e("TAG", error.getMessage(), error);
            }


        }){
            @Override
            protected Response<String> parseNetworkResponse(NetworkResponse response) {
                String str = null;
                try {
                    str = new String(response.data, "gb2312");//这里写死不好哦
                } catch (UnsupportedEncodingException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                return Response.success(str, HttpHeaderParser.parseCacheHeaders(response));
            }
        };

        quence.add(stringRequest);
    }
}
